﻿namespace Digitalmes.Application.Utils;

/// <summary>
/// 条码规则检测。
/// </summary>
public static class RuleCheckerUtil
{
    /// <summary>
    /// 校验条码规则。
    /// </summary>
    /// <param name="barcode">条码</param>
    /// <param name="rules">匹配规则集合</param>
    /// <param name="placeholder">规则中的占位字符</param>
    /// <param name="isWholeMatched">是否完整匹配。非完整匹配时条码长度不能短于规则长度，否则两者长度必须完全相等。</param>
    /// <returns></returns>
    public static bool CheckRules(string barcode, IEnumerable<string> rules, char placeholder, bool isWholeMatched)
    {
        return rules.Any(rule => CheckRule(barcode, rule, placeholder, isWholeMatched));
    }

    /// <summary>
    /// 校验条码规则。
    /// </summary>
    /// <param name="barcode">条码</param>
    /// <param name="rule">匹配规则</param>
    /// <param name="placeholder">规则中的占位字符</param>
    /// <param name="isWholeMatched">是否完整匹配。非完整匹配时条码长度不能短于规则长度，否则两者长度必须完全相等。</param>
    /// <returns></returns>
    public static bool CheckRule(string barcode, string rule, char placeholder, bool isWholeMatched)
    {
        // 长度完全匹配
        if (isWholeMatched)
        {
            if (barcode.Length != rule.Length)
            {
                return false;
            }
        }
        else
        {
            // 前缀匹配
            if (barcode.Length < rule.Length)
            {
                return false;
            }
        }

        for (int i = 0; i < rule.Length; i++)
        {
            if (rule[i] != placeholder && rule[i] != barcode[i])
            {
                return false;
            }
        }

        return true;
    }
}
